package com.paradogs.framework.core.annoations.base;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanDefinition;

import java.util.Set;

/**
 * @author: yumi
 * @date: 2023/11/18  11:00
 * @Description: TODO
 */
@Slf4j
public abstract class BaseSelector implements BeanFactoryAware {

    public BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    /**
     * @return
     */
    public final String[] scanAndHandle() {

        long startTime = System.currentTimeMillis();

        // 设置扫描路径，扫描出符合条件的 bean (接口、类等)
        String[] scanPackages = getScanPackages();

        // 获取扫描类
        BaseScanner scanner = getScanner(beanFactory);

        // 扫描出符合条件的 bean
        Set<BeanDefinition> beanDefinitions = scanner.isNeedRegister() ?
                scanner.findAndRegisterComponents(scanPackages) :
                scanner.findCandidateComponents(scanPackages);

        // 循环处理每个被扫描到的bean对象
        for (BeanDefinition beanDefinition : beanDefinitions) {
            handle(beanDefinition);
        }

        log.debug("Scan: {}, {}", scanPackages, this.getClass().getSimpleName());

        return new String[0];
    }

    /**
     * 设置扫描的路径
     * @return
     */
    public abstract String[] getScanPackages();

    /**
     * 设置要扫描的 Scanner
     * @param beanFactory
     * @return
     */
    public abstract BaseScanner getScanner(BeanFactory beanFactory);

    /**
     * 处理扫描到的 Bean
     * @param beanDefinition
     */
    public abstract void handle(BeanDefinition beanDefinition);
}
